#!/usr/bin/env python
# encoding=utf-8

import requests
from flask import *
from scpy.logger import get_logger

import dao
from stock_crawler import find_new

logger = get_logger(__file__)
app = Flask(__name__)


@app.route('/static/<path>')
def static_file(path):
    return send_from_directory('static', path)


@app.route('/')
def index():
    return render_template("index.html", title='Home', links=[
        (u'股市公告', '/announcement'),
        (u'监管措施', '/measures'),
    ])


def handler(coll, source, sort_key):
    company_name = request.args.get('companyName', '')
    page = int(request.args.get('page', 1))
    size = int(request.args.get('size', 20))
    if company_name:
        stock = dao.key_2_stock(company_name)
        alldata = dao.select(coll, filter={'stockCode': stock}, sort_key=sort_key)
        # alldata = dao.select(coll, filter={'$in': {'stockCode': stock}}, sort_key=sort_key)
    else:
        alldata = dao.select(coll, sort_key=sort_key)
    # allcount = alldata.count()
    data = alldata.skip((page - 1) * size).limit(size)
    # all_page = (allcount + size - 1) / size
    if page <= 4:
        pages = [1, 2, 3, 4, 5, 6, 7]
    else:
        pages = range(page-3, page+4)
    # if all_page <= 7:
    #     pages = range(1, all_page + 1)
    # elif page < 3 or page >= all_page - 2:
    #     pages = [1, 2, 3, '...', all_page - 2, all_page - 1, all_page]
    # else:
    #     pages = [1, '...', page - 1, page, page + 1, '...', all_page]
    datas = []
    for item in data:
        item['companyName'] = dao.stock_2_company_name(item['stockCode'])
        item['sourceStockExchange'] = (u'深', u'沪')['sse' == item[source]]
        datas.append(item)
    return datas, (page, pages), company_name


def build_template(coll, source, sort_key, title, submit_addr, template):
    datas, pages, value = handler(coll, source, sort_key)
    data = {
        'title': title,
        'datas': datas,
        'pages': pages[1],
        'page': pages[0],
        'value': value,
        'submit_addr': submit_addr,
    }
    if pages[0] > 1:
        data['pre'] = pages[0] - 1
    if pages[1][-1] > pages[0]:
        data['next'] = pages[0] + 1
    return render_template(template, **data)


@app.route('/measures', methods=['GET'])
def measures():
    try:
        return build_template('regulatoryMeasures', 'sourceStockExchange', 'regulatoryMeasuresTime', u'股市监管措施', '/measures', "measures.html")
    except:
        return render_template("404.html", title='404 not found')


@app.route('/announcement', methods=['GET'])
def announcement():
    try:
        return build_template('stockAnnouncement', 'source', 'announcementTime', u'股市公告', '/announcement', "announcement.html")
    except:
        return render_template("404.html", title='404 not found')


@app.route('/uneverknow', methods=['GET', 'POST'])
def stock_code():
    if request.method == 'POST':
        stock = request.form['stock']
        source = request.form['source']
        if not stock or not source:
            raise Exception('XXXXX')
        find_new(stock, source)
    return render_template("uneverknow.html")


@app.route('/file/<fid>')
def file_handler(fid):
    return Response(requests.get('http://10.132.23.104:10001/api/download?id=' + fid).content, mimetype='application/pdf')


if __name__ == '__main__':
    # app.run('0.0.0.0', port=9999, debug=True)

    from tornado.wsgi import WSGIContainer
    from tornado.httpserver import HTTPServer
    from tornado.ioloop import IOLoop

    http_server = HTTPServer(WSGIContainer(app))
    http_server.listen(port=9999, address='0.0.0.0')
    logger.info('tornado server started on port 9999')
    IOLoop.instance().start()
